import { reactive, computed, watch } from 'vue'
import type { PropertyPanelProps, EventConfig } from '../types'
import Modeling from 'bpmn-js/lib/features/modeling/Modeling.js'
import type { Moddle } from 'bpmn-moddle'
import type Canvas from 'diagram-js/lib/core/Canvas'

export function useEventConfig(props: PropertyPanelProps) {
  const eventConfig = reactive<EventConfig>({
    eventDefinitionType: '',
    messageName: '',
    messageId: '',
    signalName: '',
    signalId: '',
    timerDefinitionType: '',
    timerDefinition: '',
  })

  const showEventConfig = computed(() => {
    const type = props.currentElement?.type || ''
    return [
      'bpmn:StartEvent',
      'bpmn:IntermediateCatchEvent',
      'bpmn:IntermediateThrowEvent',
      'bpmn:EndEvent',
      'bpmn:BoundaryEvent'
    ].includes(type)
  })

  const generateUniqueId = (prefix: string) => {
    return `${prefix}_${Date.now()}_${Math.floor(Math.random() * 1000)}`
  }

  const handleEventChange = () => {
    if (!props.currentElement || !props.modeler) return

    const modeling = props.modeler.get('modeling') as Modeling
    const moddle = props.modeler.get('moddle') as Moddle
    const rootElement = props.modeler.get<Canvas>('canvas').getRootElement()
    const rootBo = rootElement.businessObject

    // 1. 首先清除现有的事件定义
    const currentEventDefinitions = props.currentElement.businessObject.eventDefinitions || []
    if (currentEventDefinitions.length > 0) {
      // 如果是消息或信号事件，从根元素中移除旧的引用
      const oldDefinition = currentEventDefinitions[0]
      if (oldDefinition.$type === 'bpmn:MessageEventDefinition' && oldDefinition.messageRef) {
        if (rootBo.$parent && rootBo.$parent.rootElements) {
          const index = rootBo.$parent.rootElements.findIndex(
            (el: any) => el.id === oldDefinition.messageRef.id
          )
          if (index !== -1) {
            rootBo.$parent.rootElements.splice(index, 1)
          }
        }
      } else if (oldDefinition.$type === 'bpmn:SignalEventDefinition' && oldDefinition.signalRef) {
        if (rootBo.$parent && rootBo.$parent.rootElements) {
          const index = rootBo.$parent.rootElements.findIndex(
            (el: any) => el.id === oldDefinition.signalRef.id
          )
          if (index !== -1) {
            rootBo.$parent.rootElements.splice(index, 1)
          }
        }
      }
    }

    // 2. 创建新的事件定义
    const eventDefinitions = []

    if (eventConfig.eventDefinitionType === 'message') {
      const messageId = eventConfig.messageId || generateUniqueId('Message')
      const messageRef = moddle.create('bpmn:Message', {
        id: messageId,
        name: eventConfig.messageName
      })

      const messageEventDefinition = moddle.create(
        'bpmn:MessageEventDefinition',
        {
          id: generateUniqueId('MessageEventDefinition'),
          messageRef
        }
      )

      eventDefinitions.push(messageEventDefinition)

      // 确保根元素存在
      if (!rootBo.$parent) {
        rootBo.$parent = moddle.create('bpmn:Definitions', {
          targetNamespace: 'http://flowable.org/bpmn'
        })
      }
      if (!rootBo.$parent.rootElements) {
        rootBo.$parent.rootElements = []
      }
      // 添加新的消息引用
      if (!rootBo.$parent.rootElements.find((el: any) => el.id === messageRef.id)) {
        rootBo.$parent.rootElements.push(messageRef)
      }

    } else if (eventConfig.eventDefinitionType === 'signal') {
      // 类似的处理信号事件
      const signalId = eventConfig.signalId || generateUniqueId('Signal')
      const signalRef = moddle.create('bpmn:Signal', {
        id: signalId,
        name: eventConfig.signalName
      })

      const signalEventDefinition = moddle.create(
        'bpmn:SignalEventDefinition',
        {
          id: generateUniqueId('SignalEventDefinition'),
          signalRef
        }
      )

      eventDefinitions.push(signalEventDefinition)

      // 确保根元素存在
      if (!rootBo.$parent) {
        rootBo.$parent = moddle.create('bpmn:Definitions', {
          targetNamespace: 'http://flowable.org/bpmn'
        })
      }
      if (!rootBo.$parent.rootElements) {
        rootBo.$parent.rootElements = []
      }
      // 添加新的信号引用
      if (!rootBo.$parent.rootElements.find((el: any) => el.id === signalRef.id)) {
        rootBo.$parent.rootElements.push(signalRef)
      }

    } else if (eventConfig.eventDefinitionType === 'timer') {
      const timerDefinition: Record<string, unknown> = {
        id: generateUniqueId('TimerEventDefinition')
      }

      const timeType = eventConfig.timerDefinitionType
      if (timeType) {
        const expression = moddle.create('bpmn:FormalExpression', {
          id: generateUniqueId('Expression'),
          body: eventConfig.timerDefinition
        })

        switch (timeType) {
          case 'timeDate':
            timerDefinition.timeDate = expression
            break
          case 'timeDuration':
            timerDefinition.timeDuration = expression
            break
          case 'timeCycle':
            timerDefinition.timeCycle = expression
            break
        }
      }

      eventDefinitions.push(moddle.create('bpmn:TimerEventDefinition', timerDefinition))
    }

    // 3. 更新元素属性
    modeling.updateProperties(props.currentElement, {
      eventDefinitions
    })
  }

  watch(
    () => props.currentElement,
    (element) => {
      if (element && showEventConfig.value) {
        const eventDefinitions = element.businessObject.eventDefinitions || []
        if (eventDefinitions.length > 0) {
          const definition = eventDefinitions[0]
          if (definition.$type === 'bpmn:MessageEventDefinition') {
            eventConfig.eventDefinitionType = 'message'
            eventConfig.messageId = definition.messageRef?.id || ''
            eventConfig.messageName = definition.messageRef?.name || ''
          } else if (definition.$type === 'bpmn:SignalEventDefinition') {
            eventConfig.eventDefinitionType = 'signal'
            eventConfig.signalId = definition.signalRef?.id || ''
            eventConfig.signalName = definition.signalRef?.name || ''
          } else if (definition.$type === 'bpmn:TimerEventDefinition') {
            eventConfig.eventDefinitionType = 'timer'
            if (definition.timeDate) {
              eventConfig.timerDefinitionType = 'timeDate'
              eventConfig.timerDefinition = definition.timeDate.body || ''
            } else if (definition.timeDuration) {
              eventConfig.timerDefinitionType = 'timeDuration'
              eventConfig.timerDefinition = definition.timeDuration.body || ''
            } else if (definition.timeCycle) {
              eventConfig.timerDefinitionType = 'timeCycle'
              eventConfig.timerDefinition = definition.timeCycle.body || ''
            }
          }
        } else {
          eventConfig.eventDefinitionType = ''
          eventConfig.messageName = ''
          eventConfig.messageId = ''
          eventConfig.signalName = ''
          eventConfig.signalId = ''
          eventConfig.timerDefinitionType = ''
          eventConfig.timerDefinition = ''
        }
      }
    },
    { immediate: true }
  )

  return {
    eventConfig,
    showEventConfig,
    handleEventChange
  }
}
